h<%@page import="java.io.*,java.util.*,org.apache.commons.fileupload.*"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="cn.entity.News1" %>
<%@ page import="cn.NewsDaoImpl.NewsDaoImpl1" %>
<%@ page import="cn.NewsDaoImpl.NewsDaoImpl1" %>
<%@ page import="java.net.URLDecoder" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="cn.NewsDao.NewsDao1" %>
<%@ page import="cn.NewsDaoImpl.NewsDaoImpl1" %>
<%@page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
        boolean filr=   ServletFileUpload.isMultipartContent(request);
        //准备上传的文件地址
        String path="D:\\pother";
        File file = new File(path);
        //如果目录不存在，就创建目录
        if(!file.exists()){
            file.mkdir();
        }
        //判断文件表单提交是否正确
        if(filr){
             //创建文件上传的核心工厂
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //文件上传对象
            ServletFileUpload servletFileUpload  = new ServletFileUpload(fileItemFactory);
            //获取表单的文件对象
            List<FileItem> list= servletFileUpload.parseRequest(request);
            //第一大步：上传数据
            Iterator<FileItem> item=  list.iterator();
            String fieldTitle=null;
            String picPath=null;
            while (item.hasNext()){
                FileItem fileUpload=  item.next();
              boolean isfile =  fileUpload.isFormField();
              if(isfile){
                String  fieldName=  fileUpload.getFieldName();
                  if(fieldName.equals("title")){
                      fieldTitle= fileUpload.getString("utf-8");
                  }
              }else {
                  //文件名称
                  String name= URLEncoder.encode(fileUpload.getName(),"utf-8") ;
                  File file1 = new File(name);
                  if(file1.getName() !=null && !(file1.getName().equals(""))){
                      //将对应的文件上传到指定的值
                      File file2 = new File(path,URLEncoder.encode(file1.getName(),"utf-8"));
                      //完成文件写入
                      fileUpload.write(file2);
                      picPath=file2.getName();
                  }
              }
            }
            //第二大步：保存数据库信息
            News1 newsDetail = new News1();
            newsDetail.setTitle(fieldTitle);
            newsDetail.setPicPath(path+"\\"+picPath);

            NewsDao1 newsDao = new NewsDaoImpl1();
            if(newsDao.add(newsDetail)){
               request.getRequestDispatcher("news_detail.jsp").forward(request,response);
            }else {
                System.out.println("上传失败");
            }
        }
%>
</body>
</html>
